import 'dart:convert';
import 'dart:typed_data';

class RequestPacket {
  final String type;
  final String requestId;
  final String method;
  final String path;
  final Map<String, List<String>> headers;
  final Uint8List body;

  RequestPacket({
    required this.type,
    required this.requestId,
    required this.method,
    required this.path,
    required this.headers,
    required this.body,
  });

  factory RequestPacket.fromJson(Map<String, dynamic> json) {
    final headers = <String, List<String>>{};
    final headersJson = json['headers'] as Map<String, dynamic>?;
    if (headersJson != null) {
      headersJson.forEach((key, value) {
        if (value is List) {
          headers[key] = value.cast<String>();
        } else {
          headers[key] = [value.toString()];
        }
      });
    }

    Uint8List body = Uint8List(0);
    if (json['body'] != null) {
      if (json['body'] is String) {
        body = Uint8List.fromList(utf8.encode(json['body'] as String));
      } else if (json['body'] is List) {
        body = Uint8List.fromList((json['body'] as List).cast<int>());
      }
    }

    return RequestPacket(
      type: json['type'] as String? ?? '',
      requestId: json['requestId'] as String? ?? '',
      method: json['method'] as String? ?? '',
      path: json['path'] as String? ?? '',
      headers: headers,
      body: body,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'type': type,
      'requestId': requestId,
      'method': method,
      'path': path,
      'headers': headers,
      'body': body.toList(),
    };
  }

  @override
  String toString() {
    return 'RequestPacket(type: $type, requestId: $requestId, method: $method, path: $path)';
  }
}
